// components/title/title.js
var handler = require('../../utils/dataHander')
var pageChangeUtils = require("../../utils/pageChangeUtils")
var app = getApp()
Component({
  observers: {
    'index': function (index) {
      var that = this
      var selectAns = this.data.answers[index]
      var items = that.data.items
      var index = that.data.index
      //这里将选过的选项进行判断，正确就标红，错误就标绿
      var answers = items[index].answer.split("+").sort()
      if (answers.length > 1) { //如果答案长度大于1，说明是多选，进行多选题的比较
        handler.compareArr(selectAns, answers).then(res => {
          that._setRightItems(selectAns)
        }).catch(err => {
          that._setWrongItems(selectAns)
        })
      } else { //进行单选题的比较
        that.setData({
          bcA: that.data.bc_default,
          bcB: that.data.bc_default,
          bcC: that.data.bc_default,
          bcD: that.data.bc_default,
        })
        for (let i = 0; i < selectAns.length; i++) {
          const element = selectAns[i];
          if (element == answers[0]) {
            that._setRightItems(element)
          } else {
            that._setWrongItem(element)
          }
        }
      }
    }

  },
  options: {
    styleIsolation: "apply-shared"
  },
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    tishu: 0,
    items: [], //所有的题
    item: [],
    array: [],
    radio: true,
    answers: [], //用户的选项
    select: [],
    bc_default: '#FBFBFB',
    bc_select: '#CAE1FF',
    bc_right: '#98FB98',
    bc_wrong: '#FF99B4',
    bcA: '',
    bcB: '',
    bcC: '',
    bcD: '',
    index: 0,
    switchFlag: false, //页面切换时紧用bindtap事件的标记
    favArray: [], //收藏的题号数组
    wrongItem: {}, //当前做错的题
    click: 0, //每点击一次答案click都会加一，切换新题时click会归零
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //记录用户学到哪一题和选过的answers以及做错的题目
    /**
     * 必备数据 account: item.account,
              selectLib: app.globalData.selectLib,
     * @param {} e 
     */
    _record: async function (e) {
      let that = this
      let index = that.data.index
      let learnType = app.globalData.learnType
      let item = wx.getStorageSync('user')
      let answers = that.data.answers
      if (learnType == "顺序练习" || learnType == "随机练习") {
        //将做错的题目上传上去
        let res = await this._wrongRecord()
        console.log("res", res)
        if (res == "没有错题，不需要添加" || res == "collection.add:ok") {
          if (learnType == "顺序练习") {
            //添加做过题目的index，方便下次进入继续做题
            let response = await wx.cloud.database().collection("userRecord").where({
              account: item.account,
              selectLib: app.globalData.selectLib,
            }).update({
              data: {
                index: index,
                answers: answers
              }
            })
            return response.errMsg
          }
        }
        return res
      }
      return new Promise((resolve) => {
        resolve("只有顺序和随机练习上传错题")
      })
    },


    //记录用户做错的题目
    /**
     * 必备数据 account: item.account,
              selectLib: app.globalData.selectLib,
     * @param {} 
     */
    _wrongRecord: async function () {
      let item = wx.getStorageSync('user')
      let wrongItem = this.data.wrongItem
      //为了避免一开始加载页面上传空的错题，进行判断,如果是空对象，就不上传
      if (Object.getOwnPropertyNames(wrongItem).length !== 0) {
        let res = await wx.cloud.database().collection("wrongRecord").add({
          data: {
            question: wrongItem.question,
            wrongItem: wrongItem,
            account: item.account,
            selectLib: app.globalData.selectLib,
          }
        })
        return (res.errMsg)
      } else {
        return new Promise(resolve => resolve("没有错题，不需要添加"))
      }
    },
    //更新userRecord里收藏的序号
    _updateUserFav: async function (favArray) {
      let item = wx.getStorageSync('user')
      //将收藏的题序号更新到数据库userRecord中
      let res = await wx.cloud.database().collection("userRecord").where({
        account: item.account,
        selectLib: app.globalData.selectLib,
      }).update({
        data: {
          favArray: favArray
        }
      })
      return res.errMsg
    },
    //更新favRecord里收藏的题目
    _favRecord: async function (favArray) {
      let item = wx.getStorageSync('user')
      let that = this
      let title = this.data.items[this.data.index]
      let res = await pageChangeUtils.getQuestionItem(title.question)
      var favFlag = favArray.includes(res) ? true : false
      //先将更新后收藏的题号更新到数据库中
      let resMessage = await this._updateUserFav(favArray)
      if ("collection.update:ok" == resMessage) {
        let response
        if (favFlag) {
          //向数据库中添加该题目
          response = await wx.cloud.database().collection("favRecord").add({
            data: {
              account: item.account,
              selectLib: app.globalData.selectLib,
              xuhao: res,
              title: that.data.items[that.data.index]
            }
          })
        } else {
          //将数据库中该题目删掉
          response = await wx.cloud.database().collection("favRecord").where({
            account: item.account,
            selectLib: app.globalData.selectLib,
            xuhao: res,
            title: that.data.items[that.data.index]
          }).remove()
        }
        return response
      }
    },
    _addFavorite: async function (e) {
      var that = this
      var question = that.data.item.question
      let questionIndex = await pageChangeUtils.getQuestionItem(question)
      var favArray = that.data.favArray
      if (!e) { //true 表明收藏过该题，因此点击将其取消收藏
        var favIndex = favArray.findIndex(function (favArray) {
          return favArray == questionIndex
        })
        favArray.splice(favIndex, 1)
      } else {
        favArray.push(questionIndex) //否则将该题目添加到收藏里
      }
      that.setData({
        favArray: favArray,
      })
      let con = await this._favRecord(favArray)
      console.log("收藏信息更新完毕", con.errMsg)
    },


    //记录单选题选过的选项的方法
    _recordSelect(e) {
      var myAnswer = this.data.answers
      if (e == "A") {
        myAnswer[this.data.index][0] = e
      }
      if (e == "B") {
        myAnswer[this.data.index][1] = e
      }
      if (e == "C") {
        myAnswer[this.data.index][2] = e
      }
      if (e == "D") {
        myAnswer[this.data.index][3] = e
      }
      this.setData({
        answers: myAnswer
      })
    },
    //记录多选题选过的选项的方法
    _recordDuoXuan(e) {
      var myAnswer = this.data.answers
      for (let i = 0; i < myAnswer.length; i++) {
        if (this.data.index == i) {
          myAnswer[i] = e
        }
      }
      this.setData({
        answers: myAnswer
      })
    },
    _deleteWrong: async function (items) {
      let item = wx.getStorageSync('user')
      let index = this.data.index
      let wrongItem = items[index]
      let res = await wx.cloud.database().collection("wrongRecord").where({
        question: wrongItem.question,
        wrongItem: wrongItem,
        account: item.account,
        selectLib: app.globalData.selectLib,
      }).remove()
      console.log("错题删除的结果是:", res.errMsg)
    },
    btnOpClick(e) {
      var that = this;
      var select = e.detail.value
      this._recordSelect(select)
      this.setData({
        select: select,
        click: that.data.click + 1
      })
      //将选择的选项和正确答案比较
      var items = that.data.items
      var index = that.data.index
      var answer = items[index].answer
      //如果答案长度等于1，说明是单选
      if (answer.length == 1) {
        var learnType = app.globalData.learnType
        if (select === answer) {
          if (learnType == "错题练习") {
            //如果是错题练习，这里需要将做对的题目从数据库中去掉,只有第一次点击正确才能去除新题
            if (that.data.click < 2) {
              this._deleteWrong(items)
            }
          }
          //这里判断是否是最后一题，如果是最后一题，则直接显示做完了
          if (index === that.data.tishu - 1) {
            wx.showToast({
              title: '完成所有题目！'
            })
            that._showRight()
          } else {
            that._waitNextpage()
          }
        } else {
          //这里表明选择错误，将选择的选项标红
          that._recordWrongItems()
          if (select == 'A') {
            this.setData({
              bcA: that.data.bc_wrong
            });
          } else if (select == 'B') {
            this.setData({
              bcB: that.data.bc_wrong
            });
          } else if (select == 'C') {
            this.setData({
              bcC: that.data.bc_wrong
            });
          } else if (select == 'D') {
            this.setData({
              bcD: that.data.bc_wrong
            });
          }
        }
      }
    },
    checkDuoxuan: function (params) {
      var that = this
      that.setData({
        click: that.data.click + 1
      })
      //这里为什么index等于1？
      var items = that.data.items
      var index = that.data.index
      var answer = items[index].answer
      var selectItems = that.data.select.sort() //拿到选中的答案
      var answers = answer.split("+").sort() //得到正确的答案数组
      var learnType = app.globalData.learnType
      this._recordDuoXuan(selectItems)
      //将选中的答案项目和正确答案进行比较
      handler.compareArr(selectItems, answers).then(res => {
        wx.showToast({
          title: '回答正确！',
        })
        if (learnType == "错题练习") {
          if (that.data.click < 2) {
            that._deleteWrong(items)
          }
        }
        that._showRight()
        that.setData({
          switchFlag: true
        })
        if (index === that.data.tishu - 1) {
          wx.showToast({
            title: '完成所有题目！'
          })
          that._showRight()
          return
        } else {
          this.triggerEvent("fuZiTongXin", {
            type: "swichFlag"
          })
          console.log("index", that.data),
            setTimeout(
              function () {
                that.setData({
                  index: that.data.index + 1
                });
                that._setQuestion();
              }, 2000)
        }
      }).catch(err => {
        wx.showToast({
          title: '回答错误！',
          icon: "error"
        })
        that._recordWrongItems()
        //这里将选错的选项标红
        that._setWrongItems(selectItems)
      })
    },
    //记录错题的方法
    _recordWrongItems() {
      var that = this
      that.setData({
        wrongItem: that.data.items[that.data.index]
      })
    },
    //设置单选题错误的选项
    _setWrongItem: function (e) {
      if (e == "A") {
        this.setData({
          bcA: this.data.bc_wrong
        })
      }
      if (e == "B") {
        this.setData({
          bcB: this.data.bc_wrong
        })
      }
      if (e == "C") {
        this.setData({
          bcC: this.data.bc_wrong
        })
      }
      if (e == "D") {
        this.setData({
          bcD: this.data.bc_wrong
        })
      }
    },
    _setWrongItems: function (e) {
      this.setData({
        bcA: this.data.bc_default,
        bcB: this.data.bc_default,
        bcC: this.data.bc_default,
        bcD: this.data.bc_default,
      })
      for (let i = 0; i < e.length; i++) {
        if (e[i] == "A") {
          this.setData({
            bcA: this.data.bc_wrong
          })
        }
        if (e[i] == "B") {
          this.setData({
            bcB: this.data.bc_wrong
          })
        }
        if (e[i] == "C") {
          this.setData({
            bcC: this.data.bc_wrong
          })
        }
        if (e[i] == "D") {
          this.setData({
            bcD: this.data.bc_wrong
          })
        }
      }
    },
    _waitNextpage: function () {
      var that = this
      wx.showToast({
        title: '回答正确!',
        duration: 2000,
      })
      that.setData({
        switchFlag: true
      })
      this.triggerEvent("fuZiTongXin", {
        type: "swichFlag"
      })
      that._showRight()
      setTimeout(function () {
        that._nextQuestion()
      }, 2000)
    },
    _bindPickerChange: function (e) {
      console.log("_bindPickerChange", e)
      this.setData({
        index: parseInt(e)
      })
      this._setQuestion();
    },
    _setQuestion() {
      this._record(this.data.index).then(res => {
        console.log("userRecord和WrongRecord上传完毕", res)
      })
      var that = this;
      var i = that.data.index
      var selected = that.data.answers[i]
      if (!selected) { //selected为false代表该选项没选过
        that.setData({
          bcA: that.data.bc_default,
          bcB: that.data.bc_default,
          bcC: that.data.bc_default,
          bcD: that.data.bc_default,
        })
      }
      that.setData({
        item: []
      })
      setTimeout(function () {
        that.setData({
          item: that.data.items[i],
          radio: that.data.items[i].answer.length > 1 ? false : true,
          switchFlag: false,
          select: [],
          click: 0,
          wrongItem: {},
        })
        //在这里将问题的题目序号找出来
        var item = that.data.item
        pageChangeUtils.getQuestionItem(item.question).then(res => {
          var questionIndex = res
          if (that.data.favArray.includes(questionIndex)) {
            //将问题序号传给父组件
            that.triggerEvent("fuZiTongXin", {
              type: "!swichFlag",
              value: true
            })
          } else {
            that.triggerEvent("fuZiTongXin", {
              type: "!swichFlag",
              value: false
            })
          }
        })
      }, 0)
    },
    _nextQuestion: function () {
      var that = this
      //只要不是最后一道题，就做下一题
      that.setData({
        index: this.data.index + 1
      });
      that._setQuestion({
        value: that.data.index
      });
    },
    _lastQuestion: function () {
      //这里回到上一题时需要显示出之前的答案
      var that = this;
      this.setData({
        index: this.data.index - 1
      });
      that._setQuestion({
        value: that.data.index
      });
    },
    _setRightItems: function (e) {
      var that = this;
      if (e.length > 1) {
        for (let i = 0; i < e.length; i++) {
          this._setRightItems(e[i])
        }
      } else {
        if (e === 'A') {
          this.setData({
            bcA: that.data.bc_right
          });
        }
        if (e === 'B') {
          this.setData({
            bcB: that.data.bc_right
          });
        }
        if (e === 'C') {
          this.setData({
            bcC: that.data.bc_right
          });
        }
        if (e === 'D') {
          this.setData({
            bcD: that.data.bc_right
          });
        }
      }
    },
    _showRight() {
      var that = this;
      that.setData({
        select: []
      })
      var e = that.data.item.answer
      if (e.length == 1) {
        //说明是单选
        that._setRightItems(e)
      } else {
        var answers = e.split("+")
        this.setData({
          bcA: that.data.bc_default,
          bcB: that.data.bc_default,
          bcC: that.data.bc_default,
          bcD: that.data.bc_default,
          select: answers
        })
        for (let i = 0; i < e.length; i++) {
          that._setRightItems(e[i])
        }
      }
    },



    async _getFromSql(item, learnType) {
      var that = this
      /**
       * 现在需要从数据库拿数据
       * 1.需要拿userRecord
       * 2.需要拿favRecord
       */
      //1.需要拿userRecord
      if (learnType == "顺序练习") {
        let res = await wx.cloud.database().collection("userRecord").where({
          account: item.account,
          selectLib: app.globalData.selectLib,
        }).get()
        console.log("_getFromSql", res)
        //这里如果第一次进页面是没有index和answers的
        let index = res.data[0].index
        let answers = res.data[0].answers
        let favArray = res.data[0].favArray
        if ((typeof (index) !== 'undefined') && (typeof (answers) !== 'undefined')) {
          that.setData({
            index: res.data[0].index,
            answers: res.data[0].answers,
          })
        }
        if (typeof (favArray) !== 'undefined') {
          that.setData({
            favArray: res.data[0].favArray
          })
        }
        return (res.errMsg)
      } else {
        //如果不是随机练习，则只需要拿收藏题目的序号就行
        let res = await wx.cloud.database().collection("userRecord").where({
          account: item.account,
          selectLib: app.globalData.selectLib,
        }).get()
        let favArray = res.data[0].favArray
        if (typeof (favArray) !== 'undefined') {
          that.setData({
            favArray: res.data[0].favArray
          })
        }
        return (res.errMsg)
      }
    }


  },
  lifetimes: {
    attached() {
      var that = this
      var practiceFlag = app.globalData.practiceFlag
      if (practiceFlag) {
        var subject = app.globalData.practiceWrong
      } else {
        var subject = wx.getStorageSync('subject')
      }
      var len = subject.length
      var answers = new Array(len);
      for (let i = 0; i < answers.length; i++) {
        var answerArr = new Array(4)
        answers[i] = answerArr
        for (let p = 0; p < answerArr.length; p++) {
          answers[i][p] = ""
        }
      }
      that.setData({
        items: subject,
        tishu: len,
        answers: answers,
      })
      var learnType = app.globalData.learnType
      let item = wx.getStorageSync('user')
      that._getFromSql(item, learnType).then(res => {
        console.log("_getFromSql", res)
        //修改其他组件的index
        that.triggerEvent("fuZiTongXin", {
          type: "updateIndex",
          value: that.data.index
        })
        this._setQuestion();
      })
    }
  }
})